package edu.mju.eduorder.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.mju.commonutils.JwtUtils;
import edu.mju.commonutils.ReturnCode;
import edu.mju.eduorder.entity.StudyOrder;
import edu.mju.eduorder.service.StudyOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author xiaoxin
 * @since 2020-10-05
 */
@RestController
@RequestMapping("/eduorder/study-order")
public class StudyOrderController {
    @Autowired
    private StudyOrderService studyOrderService;

    /**
     * 生成订单
     * @param courseId 课程id
     * @param request 获取服务器的token
     * @return orderId
     */
    @PostMapping("/createOrder/{courseId}")
    public ReturnCode createOrder(@PathVariable String courseId,
                                  HttpServletRequest request){
        //解析前端用户数据
        String userIdByJwtToken = JwtUtils.getUserIdByJwtToken(request);

        //防止前端用户数据伪造token
        if("".equals(userIdByJwtToken) || userIdByJwtToken==null){
            return ReturnCode.fail().code(28004);
        }

        String orderId = studyOrderService.createOrder(courseId,userIdByJwtToken);

        Map<String,Object> map = new HashMap<>();
        map.put("orderId",orderId);
        return ReturnCode.success().data(map);
    }

    @GetMapping("/getOrderInfo/{orderId}")
    public ReturnCode getOrderInfo(@PathVariable String orderId){
        QueryWrapper<StudyOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        StudyOrder order = studyOrderService.getOne(wrapper);

        Map<String,Object> map = new HashMap<>();
        map.put("item",order);
        return ReturnCode.success().data(map);
    }

    /**
     * 根据课程id和用户id查询订单表中订单状态
     * @param courseId 课程id
     * @param userId 用户id
     * @return 已支付：true 未支付：false
     */
    @GetMapping("/isBuyCourse/{courseId}/{userId}")
    public boolean isBuyCourse(@PathVariable String courseId,@PathVariable String userId){
        QueryWrapper<StudyOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",userId);
        //支付状态：已支付
        wrapper.eq("status",1);

        int count = studyOrderService.count(wrapper);

        //已支付返回True，否则返回false
        if(count>0){
            return true;
        }else {
            return false;
        }

    }

}

